// pages/Welcome/Welcome.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { getToken , codeLogin , queryWechatPhone , getCode } from '../../api/login';
import { getUser , updateUserPhone } from '../../api/user';
import { ACCESS_TOKEN } from '../../utils/types';
import { isNumberOr_Letter } from '../../utils/util';
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    parentUserId: '', // 推荐人ID
    assetsAddress: assetsAddress,
    brandName: app.globalData.global.brandName,
    show: false,
    showPhoneCode: false,
    code: '', // 验证码
    num: 60,
    params: '',
    pathName: '',
    showPrivacyAuthor: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.scene){
      const scene = decodeURIComponent(options.scene)
      var arr = scene.split('---');
      console.log(scene,'scene')
      this.setData({
        parentUserId: arr.length > 1 ? arr[0] : scene,
        params: arr.length > 1 ? arr[1] : '',
        pathName: arr.length > 2 ? arr[2] : '',
      })
      wx.setStorageSync('parentUserId', arr.length > 1 ? arr[0] : scene)
      wx.setStorageSync('params', arr.length > 1 ? arr[1] : '')
      wx.setStorageSync('pathName', arr.length > 2 ? arr[2] : '')
    }
    this.login();
    var _this = this;
    if (wx.onNeedPrivacyAuthorization){
      wx.onNeedPrivacyAuthorization((resolve) => {
        console.log('触发弹窗')
        // 触发弹窗
        _this.setData({
          showPrivacyAuthor: true,
        })
        _this.resolvePrivacyAuthorization = resolve
      })
    }  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 登录
  login(){
    var expires_in = wx.getStorageSync('expires_in');
    console.log(expires_in,'expires_in');
    // wx.switchTab({
    //   url: '/pages/Tabbar/Home/Home',
    // });
    // return;
    // 获取服务器token
    getToken().then(res => {
      let _this = this;
      if(res.success){
          wx.setStorageSync(ACCESS_TOKEN, res[ACCESS_TOKEN]);
          // 登录
          wx.login({
            success: logRes => {
              // 发送 res.code 到后台换取 openId, sessionKey, unionId
              console.log(logRes,'logRes')
              if (logRes.code) {
                codeLogin(logRes.code,_this.data.parentUserId)
                .then(rres => {
                  console.log(rres,'第一次登录返回的rres')
                  if(rres.success){
                      wx.setStorageSync(ACCESS_TOKEN, rres.access_token);
                      wx.setStorageSync('expires_in', rres.expires_in);
                      setTimeout(() => {
                        getUser()
                        .then(user => {
                          if(user.success){
                            // 判断注册时间
                            var careateTime = user.data.userCreateTime.replace(/-/g,'/');
                            var dataDiff = new Date().getTime() - new Date(careateTime).getTime();
                            console.log(dataDiff,'dataDiff')
                            if(dataDiff < 60000){
                              if(user.data.phone.length == 11){
                                wx.setStorageSync('userId', user.data.userId)
                                wx.setStorageSync('phone', user.data.phone)
                                wx.switchTab({
                                  url: '/pages/Tabbar/Home/Home',
                                })
                              }else{
                                // Dialog.confirm({
                                //   title: '温馨提示',
                                //   message: '弹窗内容',
                                //   confirmButtonOpenType: 'getPhoneNumber'
                                // }).then((e) => {
                                //   console.log(e.detail.code)
                                //   // on close
                                // }).catch(() => {
                                //   wx.setStorageSync('userId', user.data.userId)
                                //   wx.setStorageSync('phone', user.data.phone)
                                //   wx.switchTab({
                                //     url: '/pages/Tabbar/Home/Home',
                                //   })
                                // });
                                wx.setStorageSync('userId', user.data.userId)
                                wx.setStorageSync('phone', user.data.phone)
                                wx.requirePrivacyAuthorize({
                                  success: () => {
                                    // 用户同意授权
                                    // 继续小程序逻辑
                                    wx.switchTab({
                                      url: '/pages/Tabbar/Home/Home',
                                    })
                                  },
                                  fail: () => {
                                    console.log('拒绝')
                                    wx.switchTab({
                                      url: '/pages/Tabbar/Home/Home',
                                    })
                                  }, // 用户拒绝授权
                                  complete: () => {}
                                })
                                // _this.setData({
                                //   show: true,
                                // })
                              }
                            }else{
                              wx.setStorageSync('phone', user.data.phone)
                              wx.setStorageSync('userId', user.data.userId)
                              wx.switchTab({
                                url: '/pages/Tabbar/Home/Home',
                              })
                            }
                          }
                        })
                      }, 500);
                  }
                })
              } else {
                wx.showToast({
                  title: logRes.errMsg,
                  icon: 'none',
                })
              }
            },
          })
      }else{
          wx.showToast({
              title: res.errMessage,
              icon: 'none'
          })
      }
    })
  },

  getphonenumber(e){
    let _this = this;
    console.log(e.detail.code);
    if(e.detail.code){
      queryWechatPhone({code: e.detail.code})
      .then(res => {
        if(res.success){
          _this.setData({
            phone: res.data.phoneNumber,
            // showPhoneCode: true,
          })
          _this.submit();
          // _this.getCode();
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      }).catch(()=>{
        wx.switchTab({
          url: '/pages/Tabbar/Home/Home',
        })
      })
    }else{
      wx.switchTab({
        url: '/pages/Tabbar/Home/Home',
      })
    }
  },
  onClose(){
    this.setData({
      show: false,
      showPhoneCode: false,
    })
    wx.switchTab({
      url: '/pages/Tabbar/Home/Home',
    })
  },
  confirm(){
    this.submit();
  },
  // 更改手机号
  submit(){
    let _this = this;
    if(_this.data.phone == '' || _this.data.phone.length != 11 || !isNumberOr_Letter(_this.data.phone)){
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none',
      })
      return;
    }
    // if(_this.data.code == ''){
    //   wx.showToast({
    //     title: '请输入正确的手机号',
    //     icon: 'none',
    //   })
    //   return;
    // }
    updateUserPhone({newPhone: _this.data.phone})
    .then(res => {
      if(res.success){
        wx.showToast({
          title: '手机号绑定成功！',
          icon: 'none',
        })
        wx.setStorageSync('phone', _this.data.phone)
        wx.switchTab({
          url: '/pages/Tabbar/Home/Home',
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
        // wx.switchTab({
        //   url: '/pages/Tabbar/Home/Home',
        // })
      }
    })
  },
  // 获取验证码
  getCode(){
    let _this = this;
    if(_this.data.num != 60){
      return;
    }
    if(_this.data.phone == '' || _this.data.phone.length != 11 || !isNumberOr_Letter(_this.data.phone)){
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none',
      })
      return;
    }
    _this.setData({
      num: _this.data.num - 1,
    })
    var timer = setInterval(() => {
      _this.setData({
        num: _this.data.num - 1,
      })
      if (_this.data.num == 0) {
        clearInterval(timer)
        _this.setData({
          num: 60,
        })
      }
    }, 1000)
    getCode(_this.data.phone)
    .then(res => {
      if(res.success){
        wx.showToast({
          title: res.data,
          icon: 'none',
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  handleAgreePrivacyAuthorizationFun(){
    console.log('同意之后的回调');
    this.setData({
      show: true,
    })
  },
  disagreePrivacyAuthorization(){
    this.resolvePrivacyAuthorization({ event: 'disagree' });
    wx.switchTab({
      url: '/pages/Tabbar/Home/Home',
    })
  },
})